package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.domain.StuClassDO;
import com.jinzhi.jzweb.domain.StudentClassesDO;
import com.jinzhi.jzweb.domain.OrganizationNewsDO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 
 * <pre>
 * 班级表
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/studentClasses")
public class ClassesController extends BaseController {
    @Autowired
    private CoursesService coursesService;
    @Autowired
	private ClassesService classesService;
    @Autowired
    private StuClassService stuClassService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrganizationNewsService organizationNewsService;

	@GetMapping()
	@RequiresPermissions("jzweb:studentClasses:studentClasses")
	String Classes(){
	    return "jzweb/studentClasses/studentClasses";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:studentClasses:studentClasses")
	public Result<Page<StudentClassesDO>> list(HttpServletRequest req, StudentClassesDO classesDTO){
		Wrapper<StudentClassesDO> wrapper = new EntityWrapper<StudentClassesDO>().orderBy("id", false);

		if (classesDTO.getName() != null){
			wrapper.like("name",classesDTO.getName());
		}
		//查询用户角色
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			Object orgId = req.getSession().getAttribute("orgId");
			if (orgId != null){
				wrapper.eq("org_id",orgId);
			}else {
				wrapper.eq("org_id",this.getUser().getOrgId());
			}

			if(roleName.contains("班主任")){
				wrapper.eq("creater_id",this.getUserId());
			}
		}else{
			if (StringUtils.isNotBlank(classesDTO.getOrgName())){
				Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name",classesDTO.getOrgName());
				List<OrganizationNewsDO>  organizationNewsDOS = organizationNewsService.selectList(orWrapper);
				String str = "";
				for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS){
					str = str + organizationNewsDO.getId() + ",";
				}
				wrapper.and();
				if(StringUtils.isNotBlank(str)){
					wrapper.in("org_id",str.substring(0,str.length()-1));
				}else{
					wrapper.eq("org_id",null);
				}
			}
		}

		if (StringUtils.isNotBlank(classesDTO.getCreaterName())){
			Wrapper<UserDO> uWrapper = new EntityWrapper<UserDO>().like("name",classesDTO.getCreaterName());
			List<UserDO>  userDOS = userService.selectList(uWrapper);
			String str = "";
			for (UserDO userDO : userDOS){
				str = str + userDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("user_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("user_id",null);
			}
		}

		Page<StudentClassesDO> page = classesService.selectPage(getPage(StudentClassesDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
            StudentClassesDO obj = (StudentClassesDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getName());
				}
			}
			if (obj.getOrgId() != null){
				OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
				if (organizationNewsDO != null) {
					obj.setOrgName(organizationNewsDO.getName());
				}
			}
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if (obj.getUpdaterId() != null){
				UserDO userDO = userService.selectById(obj.getUpdaterId());
				if (userDO != null) {
					obj.setUpdateName(userDO.getUsername());
				}
			}

            Wrapper<StuClassDO> sWrapper = new EntityWrapper<StuClassDO>();
            sWrapper.eq("class_id", obj.getId());
            sWrapper.eq("status", 1);
            List<StuClassDO>  stuClassDOS = stuClassService.selectList(sWrapper);
            obj.setStudentNum(stuClassDOS.size());

            Wrapper<StuClassDO> sWrapper2 = new EntityWrapper<StuClassDO>();
            sWrapper2.eq("class_id", obj.getId());
            sWrapper2.eq("status", 0);
            List<StuClassDO>  stuClassDOS2 = stuClassService.selectList(sWrapper2);
            obj.setStudentNumExamine(stuClassDOS2.size());

            list.add(obj);
		}
        if(list.size()>0) {
            page.setRecords(list);
        }else {
            list=null;
            page.setRecords(list);
        }
        return Result.ok(page);
	}

    @GetMapping("/add")
    @RequiresPermissions("jzweb:studentClasses:add")
    String add(Model model){
        String roleName = getRoleNames();
        //Map<String, String> map = new HashMap<>();

        if (!roleName.contains("超级用户角色")) {
            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(this.getUser().getOrgId());
            if(organizationNewsDO != null){
                model.addAttribute("orgName",organizationNewsDO.getName());
                model.addAttribute("orgId",organizationNewsDO.getId());
            }else{
                model.addAttribute("orgName",this.getUser().getOrgName());
                model.addAttribute("orgId",this.getUser().getOrgId());
            }
        } else {
            model.addAttribute("orgName",this.getUser().getOrgName());
            model.addAttribute("orgId",this.getUser().getOrgId());
        }
        return "jzweb/studentClasses/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:studentClasses:edit")
    String edit(@PathVariable("id") Long id, Model model){
        StudentClassesDO studentClasses = classesService.selectById(id);
        model.addAttribute("studentClasses", studentClasses);
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(studentClasses.getOrgId());
        if(organizationNewsDO != null){
            model.addAttribute("orgName",organizationNewsDO.getName());
            model.addAttribute("orgId",organizationNewsDO.getId());
        }else{
            model.addAttribute("orgName",this.getUser().getOrgName());
            model.addAttribute("orgId",this.getUser().getOrgId());
        }
        return "jzweb/studentClasses/edit";
    }


    @Log("添加班级表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:studentClasses:add")
    public Result<String> save( StudentClassesDO studentClasses){
        studentClasses.setCreaterId(this.getUserId());
        studentClasses.setUpdaterId(this.getUserId());
        classesService.insert(studentClasses);
        return Result.ok();
    }


    @Log("修改班级表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:studentClasses:edit")
    public Result<String>  update( StudentClassesDO studentClasses){
        studentClasses.setUpdaterId(this.getUserId());
        boolean update = classesService.updateById(studentClasses);
        return update ? Result.ok() : Result.fail();
    }



    @Log("删除班级表")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:chapter:remove")
    public Result<String>  remove( Long id){
        Wrapper<StuClassDO> sWrapper = new EntityWrapper<StuClassDO>();
        sWrapper.eq("class_id", id);
        sWrapper.in("status", "0,1");
        List<StuClassDO>  stuClassDOS = stuClassService.selectList(sWrapper);
        if(stuClassDOS.size()>0){
            return Result.fail("当前班级已有学生加入，不能删除！");
        }else {
            classesService.deleteById(id);
            return Result.ok();
        }
    }

    @Log("批量删除班级表")
    @PostMapping( "/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:chapter:batchRemove")
    public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
	    int num = 0;
	    if(ids.length>0){
	        for ( int a=0; a<ids.length; a++){
                Wrapper<StuClassDO> sWrapper = new EntityWrapper<StuClassDO>();
                sWrapper.eq("class_id", ids[a]);
                sWrapper.in("status", "0,1");
                List<StuClassDO>  stuClassDOS = stuClassService.selectList(sWrapper);
                if(stuClassDOS.size()>0){
                    num += 1;
                }else {
                    classesService.deleteById(ids[a]);
                }
            }
        }
	    if(num>0) {
            return Result.fail("部分班级已有学生加入，不能删除！");
        }else {
            return Result.ok();
        }
    }
}


